<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    EveBit_Library
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Public.php 1054 2011-05-26 10:27:37Z zuo.fujie $$
 * @copyright   Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Default Action
 * 
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Public.php 1054 2011-05-26 10:27:37Z zuo.fujie $$
 */
class Evebit_Controller_Action_Public extends Zend_Controller_Action {
	
	/**
	 * Get log
	 * @return Zend_Log
	 */
	public function getLog() {
		return Evebit_Application::app ()->getLog ();
	}
	/**
	 * 
	 * get Action Name
	 */
	public function _getActionName() {
		$request = $this->getRequest ();
		return $request->getModuleName () . '_' . $request->getControllerName () . '_' . $request->getActionName ();
	}
	/**
	 * 
	 * Get the current user
	 * @return User_Model_Entity_User
	 */
	public function getUser($username = "") {
		if ($username != "") {
			$user = new User_Model_Entity_User ();
			$collection = $user->getCollection ();
			$collection->addFieldToFilter ( "username", $username );
			return $collection->getFirstItem ();
		}
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			$user = Zend_Auth::getInstance ()->getIdentity ();
			return $user;
		} else {
			$user = new User_Model_Entity_User ();
			$collection = $user->getCollection ();
			$collection->addFieldToFilter ( 'select_role', 'Guest' );
			return $collection->getFirstItem ();
		}
	}
	/**
	 * Get cache
	 * @return Zend_Cache
	 */
	public function getCache() {
		return Evebit_Application::app ()->getCache ();
	}
	
	/**
	 * Get current session instance
	 * 
	 * @return Evebit_Application_Session
	 */
	public function getSession() {
		return Evebit_Application::getSession ();
	}
	
	/**
	 * Translate into current locale
	 * 
	 * e.g. 
	 * 
	 * there are to string in language file:
	 * <code>
	 * original string=show this text
	 * format string=first arg is %s
	 * </code>
	 * 
	 * then, you can tranlsate as:
	 * <code>
	 * 
	 * Evebit_Application_Session::__('original string');
	 * // result is 'show this text'
	 * 
	 * Evebit_Application_Session::__('format string', '0123');
	 * // result is 'first arg is 0123'
	 * 
	 * Evebit_Application_Session::__(array('format string', '0123'));
	 * // result is 'first arg is 0123'
	 * 
	 * </code>
	 * 
	 * @see Evebit_Application_Session::translate
	 * @param string|array $msg
	 * @return string
	 */
	public function __($msg) {
		$args = func_get_args ();
		return $this->getSession ()->translate ( $args );
	}
	
	/**
	 * 
	 * Get the current date
	 */
	public function getNow() { //$format="YYYY-MM-dd HH:mm:ss"		
		return new Zend_Date ();
	}
	
	/**
	 * upload image
	 * @param string $dir_name
	 * @param string $maxsize
	 * @return string|array|bool
	 */
	public function _uploadImage($dir_name, $maxsize = "4096kB") {
		/* @var $upload Zend_File_Transfer_Adapter_Http */
		$fullpath = RP . DS . "/media/$dir_name";
		if (! is_dir ( $fullpath )) {
			mkdir ( $fullpath, 0777, true );
		}
		$upload = new Zend_File_Transfer_Adapter_Http ();
		$upload->addValidator ( 'Count', false, array ('min' => 1, 'max' => 20 ) )->addValidator ( 'ImageSize', false, array ('minwidth' => 0, 'minheight' => 0 ) )->addValidator ( 'Size', false, array ('min' => 0, 'max' => $maxsize ) )->setDestination ( $fullpath );
		$fileInfo = $upload->getFileInfo ();
		if ($upload->isValid ()) {
			try {
				$fileName = $upload->getFileName ();
				if (is_array ( $fileName )) {
					foreach ( $fileName as $key => $name ) {
						$guid = new User_Model_Config_Source_Guid ();
						$_guid = $guid->create ();
						$newname = $this->getFilename ( $fullpath . "/", basename ( $_guid . $name ) );
						$newname = $_guid . $newname;
						$rename [] = array ('source' => $fileInfo [$key] ['tmp_name'], 'target' => $fullpath . '/' . $newname );
						$filePathArr [] = $dir_name . "/" . $newname;
					}
				
				} else {
					$guid = new User_Model_Config_Source_Guid ();
					$_guid = $guid->create ();
					$newname = $this->getFilename ( $fullpath . "/", basename ( $_guid . $fileName ) );
					$newname = $_guid . $newname;
					$rename = array ('source' => $fileInfo [$key] ['tmp_name'], 'target' => $fullpath . '/' . $newname );
					$filePathArr [] = $dir_name . "/" . $newname;
				}
				$upload->addFilter ( new Zend_Filter_File_Rename ( $rename ) );
				$upload->receive ();
				return $filePathArr;
			} catch ( Zend_File_Transfer_Exception $e ) {
				$this->getSession ()->addError ( $this->__ ( 'Bad image data: ' ) . $e->getMessage () );
				return false;
			}
		} else {
			return '';
		}
	}
	
	/**
	 * get file name
	 * @param string $dirPath
	 * @param string $fileName
	 * @return string
	 */
	public function getFilename($dirPath, $fileName) {
		if (is_file ( $dirPath . $fileName )) {
			$extension = pathinfo ( $fileName, PATHINFO_EXTENSION );
			$name = pathinfo ( $fileName, PATHINFO_FILENAME );
			return $this->getFilename ( $dirPath, $name . "1." . $extension );
		}
		return $fileName;
	}
	
	/**
	 * translate google date string to y,m,d format
	 * @param string $date
	 */
	public function transformatGoogleDate($date) {
		$retrunDate = array ();
		$date = explode ( "T", $date );
		$date = explode ( "-", $date [0] );
		$retrunDate ["year"] = $date [0];
		$retrunDate ["month"] = $date [1];
		$retrunDate ["day"] = $date [2];
		return $retrunDate;
	}
	
	/**
	 * send mail
	 * @param string $email
	 * @param string $password
	 * @param string $ssl
	 * @param string $subject
	 * @param string $content
	 * @param string $sendTo
	 * @param string $toName
	 * @return array
	 */
	public function sendMail($email, $password, $subject, $content, $sendTo, $toName = '', $ssl = 'ssl') {
		$flag = array ();
		$googleSmtp = 'smtp.gmail.com';
		$mail = new Zend_Mail ( "UTF-8" );
		$config = array ('auth' => 'login', 'username' => $email, 'password' => $password, 'ssl' => $ssl, 'port' => 465 );
		$mailTransport = new Zend_Mail_Transport_Smtp ( $googleSmtp, $config );
		if (@$_FILES ['attach'] && $_FILES ['attach'] ['tmp_name'] != '') {
			$attach = $mail->createAttachment ( file_get_contents ( $_FILES ['attach'] ['tmp_name'] ) );
			$attach->type = $_FILES ['attach'] ['type'];
			$attach->filename = $_FILES ['attach'] ['name'];
		}
		$mail->setBodyHtml ( $content );
		$mail->setSubject ( $subject );
		$mail->setFrom ( $email );
		//$sendTo = 'chen.qiao@evebit.com';
		$sendToArr = explode ( ';', $sendTo );
		if ($toName) {
			$toNameArr = explode ( ';', $toName );
		}
		foreach ( $sendToArr as $key => $send ) {
			if ($toNameArr && @$toNameArr [$key]) {
				$mail->addTo ( $send, $toNameArr [$key] );
			} else {
				$mail->addTo ( $send );
			}
			
			try {
				$rs = $mail->send ( $mailTransport );
			} catch ( Exception $e ) {
				$flag [] = $send;
			}
		}
		return $flag;
	}
	
	/**
	 * Get a part of the string without breaked word
	 * @param string $string
	 * @param int $length
	 * @return string
	 */
	public static function substrWithoutBreak($string, $length) {
		$string = self::removeHtmlTag($string);
		if (strlen ( $string ) < $length) {
			return $string;
		}
		if (substr ( $string, $length, 1 ) == ' ') {
			return substr ( $string, 0, $length ) . ' ...';
		} else {
			$nextString = substr ( $string, $length, 200 );
			$extraLength = strpos ( $nextString, ' ' );
			return substr ( $string, 0, ($length + $extraLength) ) . ' ...';
		}
	}
	
	/**
	 * Remove html tag of the string
	 * @param String $string
	 * @return string
	 */
	public static function removeHtmlTag($string){
		$filter = new Zend_Filter_StripTags();
		$string = $filter->filter($string);
		return $string;
	}
}
